package com.travel.manager.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.travel.manager.dao.CityDAO;
import com.travel.manager.service.CityService;
import common.pojo.City;
import common.util.JedisClient;
import common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityDAO cityDAO;

    @Override
    public void addCity(City city) {
        cityDAO.addCity(city);
        jedisClient.expire(CITY_LIST,0);
    }

    @Override
    public PageInfo<City> getCityList(City criteria, Integer pageNum, Integer pageSize) {
        //设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        List<City> cityList = cityDAO.getCityList(criteria);
        PageInfo<City> pageInfo = new PageInfo<>(cityList);
        return pageInfo;
    }

    @Override
    public void updateCity(City city) {
        cityDAO.updateCity(city);
        jedisClient.expire(CITY_LIST,0);
    }

    @Autowired
    private JedisClient jedisClient;

    @Value("${CITY_LIST}")
    private String CITY_LIST;

    @Override
    public List<City> getAllCityList() {
        //从redis中读取列表
        String json = jedisClient.get(CITY_LIST);
        if (json != null) {
            //如果redis中有数据就转化成java对象并返回
            try {
                return JsonUtil.getObj(json, new TypeReference<List<City>>() {
                });
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //如果redis中没有数据或者json转换异常就从数据库中查询
        List<City> cityList = cityDAO.getCityList(null);
        try {
            //将查询出的结果存入redis
            jedisClient.set(CITY_LIST, JsonUtil.getJSON(cityList));
            //jedisClient.expire(CITY_LIST,1800);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return cityList;

    }
}
